<script setup lang="ts">
  import { ref, defineEmits, computed, watch, onMounted, reactive } from 'vue';
  import { useBooleanStore } from '@/store';
  import {
    searchLibrary,
    rowTurnOn,
    rowTurnDown,
    outBatch,
    sysLibraryChange,
  } from '@/api/system-basic';
  import { Notification } from '@arco-design/web-vue';

  const emit = defineEmits(['updateArray']);
  const booleanStore = useBooleanStore();
  // 表单查询数据
  const rowNo = ref<string>('');
  const roadNo = ref<string>('');
  const shelvesCode = ref<string>('');
  const palletCode = ref<string>('');
  const isEmp = ref<string>('');
  const transferPosition = ref<string>('');
  const status = ref<string>('');
  const visible = ref<boolean>(false);

  const roadChoice = ref([
    {
      value1: '1',
      label: '巷道一',
    },
    {
      value1: '2',
      label: '巷道二',
    },
    {
      value1: '3',
      label: '巷道三',
    },
    {
      value1: '4',
      label: '巷道四',
    },
    {
      value1: '5',
      label: '巷道五',
    },
    {
      value1: '6',
      label: '巷道六',
    },
  ]);
  const form = reactive({
    rowNo: '',
    status: '',
    isEmpty: '',
    shelvesCode: '',
    palletCode: '',
    hierarchy: '',
    col: '',
  });
  const statusChoice = [
    {
      value: '1',
      label: '空闲',
    },
    {
      value: '2',
      label: '已分配',
    },
    {
      value: '3',
      label: '已占用',
    },
  ];
  const isEmptyChoice = [
    {
      value: 'Y',
      label: '是',
    },
    {
      value: 'N',
      label: '否',
    },
  ];
  const changedModal = ref<boolean>(false);
  const pageSize = ref<number>(10);
  const pageNumber = ref<number>(1);
  // 发送搜索数据
  const flowQueryData = ref({
    searchParams: computed(() => ({
      rowNo: rowNo.value,
      isEmp: isEmp.value,
      shelvesCode: shelvesCode.value,
      palletCode: palletCode.value,
      transferPosition: transferPosition.value,
      status: status.value,
    })),
    pageParameter: computed(() => ({
      rows: pageSize.value,
      page: pageNumber.value,
    })),
  });
  // 表格数据
  const newData = ref<any>();
  async function handleSearch() {
    newData.value = await searchLibrary(flowQueryData.value);
    emit('updateArray', newData.value);
  }
  // 重置
  function reset() {
    rowNo.value = '';
    isEmp.value = '';
    shelvesCode.value = '';
    palletCode.value = '';
    transferPosition.value = '';
    status.value = '';
    handleSearch();
  }

  // 开启巷道
  async function open() {
    const data = await rowTurnOn({ roadway: roadNo.value });
    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });

      handleSearch();
      visible.value = false;
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
  }

  // 关闭巷道
  async function close() {
    const data = await rowTurnDown({ roadway: roadNo.value });
    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });

      handleSearch();
      visible.value = false;
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
  }

  // 修改
  function changed() {
    if (booleanStore.listThree[0]?.value.length !== 1) {
      Notification.error({
        title: '失败',
        content: '请勾选一条记录',
        closable: true,
      });
    } else {
      const selectedTableData = newData.value?.list.filter((item: any) =>
        booleanStore.listThree[0].value?.includes(item.PAGEHELPER_ROW_ID)
      );
      console.log(selectedTableData[0]);
      Object.assign(form, selectedTableData[0]);
      form.rowNo = selectedTableData[0].rowNoCode;
      form.status = selectedTableData[0].statusCode;
      form.isEmpty = selectedTableData[0].isEmptyCode;
      changedModal.value = true;
    }
  }

  const formRef = ref<any>('');

  const rules = {
    rowNo: [{ required: true, message: '不能为空' }],
    status: [{ required: true, message: '不能为空' }],
    isEmpty: [{ required: true, message: '不能为空' }],
    hierarchy: [{ required: true, message: '不能为空' }],
    col: [{ required: true, message: '不能为空' }],
  };

  // 一键叫箱
  async function outBatchList() {
    if (booleanStore.listThree[0]?.value.length === 0) {
      Notification.error({
        title: '失败',
        content: '请勾选一条记录',
        closable: true,
      });
    } else {
      const dataInfo: any[] = []; // 在循环外声明数组
      console.log(booleanStore.listThree[0]);
      booleanStore.listThree[0].value.forEach((val: any) => {
        const matchedItems = newData.value?.list.filter(
          (item: any) => item.PAGEHELPER_ROW_ID === val
        );
        matchedItems.forEach((item_: any) => {
          dataInfo.push({
            palletCode: item_.palletCode || '',
            roadway: item_.rowNo || '',
            startCode: item_.shelvesCode || '',
          }); // 将匹配的项添加到数组中
        });
      });
      booleanStore.toggleBool(0);
      try {
        const data = await outBatch({ codes: dataInfo });
        if (data.retCode === '200') {
          booleanStore.toggleBool(0);
          Notification.success({
            title: '成功',
            content: data.message,
            closable: true,
          });
          booleanStore.toggleBool4(5);
          handleSearch();
        } else {
          Notification.error({
            title: '失败',
            content: data.message,
            closable: true,
          });
          booleanStore.toggleBool(0);
          booleanStore.toggleBool4(5);
          handleSearch();
        }
      } catch (error) {
        booleanStore.toggleBool(0);
        Notification.error({
          title: '失败',
          content: '网络异常',
          closable: true,
        });
      }
    }
  }

  // 确认修改
  async function changedOK(done: any) {
    const res = await formRef.value.validate();
    if (res) {
      done(false);
    } else {
      const response = await sysLibraryChange(form);
      if (response.retCode === '200') {
        Notification.success({
          title: '成功',
          content: response.message,
          closable: true,
        });
        // 情况form的值
        Object.keys(form).forEach((key) => {
          (form as Record<string, any>)[key] = '';
        });
        changedModal.value = false;
        handleSearch();
      } else {
        Notification.error({
          title: '失败',
          content: response.message ? response.message : '修改失败',
          closable: true,
        });
        changedModal.value = false;
      }
      booleanStore.toggleBool4(5);
      done();
    }
  }
  // 监听分页
  watch([() => booleanStore.pageNum, () => booleanStore.pageSize], () => {
    if (booleanStore.num5 === 39) {
      pageNumber.value = booleanStore.pageNum;
      pageSize.value = booleanStore.pageSize;
      handleSearch();
    }
  });
  onMounted(() => {
    handleSearch();
  });
</script>

<template>
  <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
    <a-col :span="6">
      <div>
        <a-select v-model="rowNo" allow-clear placeholder="巷道" size="large">
          <a-option
            v-for="item in roadChoice"
            :key="item.value1"
            :value="item.value1"
            >{{ item.label }}
          </a-option>
        </a-select>
      </div>
    </a-col>
    <a-col :span="6">
      <div>
        <a-input
          v-model="shelvesCode"
          allow-clear
          placeholder="货位编码"
          size="large"
        />
      </div>
    </a-col>
    <a-col :span="6">
      <div>
        <a-input
          v-model="palletCode"
          allow-clear
          placeholder="操作盘编码"
          size="large"
        />
      </div>
    </a-col>
    <a-col :span="6">
      <div>
        <a-select
          v-model="isEmp"
          allow-clear
          placeholder="是否空箱"
          size="large"
        >
          <a-option value="Y">是</a-option>
          <a-option value="N">否</a-option>
        </a-select>
      </div>
    </a-col>
  </a-row>
  <a-row class="grid-demo" :gutter="{ md: 8, lg: 24, xl: 32 }">
    <a-col :span="6">
      <div>
        <a-select
          v-model="transferPosition"
          allow-clear
          placeholder="是否移库位"
          size="large"
        >
          <a-option value="Y">是</a-option>
          <a-option value="N">否</a-option>
        </a-select>
      </div>
    </a-col>
    <a-col :span="6">
      <div>
        <a-select
          v-model="status"
          allow-clear
          placeholder="货架状态"
          size="large"
        >
          <a-option value="3">占用</a-option>
          <a-option value="2">已分配</a-option>
          <a-option value="1">空闲</a-option>
        </a-select>
      </div>
    </a-col>
  </a-row>
  <div class="btn-group">
    <a-button type="primary" size="large" @click="handleSearch">查询</a-button>
    <a-button class="btn-reset" size="large" @click="reset">重置查询</a-button>
    <a-button
      type="primary"
      style="margin-left: 8px"
      size="large"
      @click="changed"
      >修改</a-button
    >
    <a-button
      type="primary"
      class="btn-reset"
      size="large"
      @click="booleanStore.toggleBool2(9)"
      >查询当前位置出库任务</a-button
    >
    <a-button
      type="primary"
      class="btn-reset"
      size="large"
      @click="visible = true"
      >巷道开关</a-button
    >
    <a-button
      type="primary"
      class="btn-reset"
      size="large"
      @click="outBatchList"
      >一键叫箱</a-button
    >
  </div>
  <a-modal
    :visible="visible"
    unmount-on-close
    :footer="false"
    @cancel="visible = false"
  >
    <template #title> 确认信息填写 </template>
    <div class="drawer-class">
      <div class="div-flex">
        <a-select v-model="roadNo" allow-clear placeholder="巷道" size="large">
          <a-option
            v-for="item in roadChoice"
            :key="item.value1"
            :value="item.value1"
            >{{ item.label }}</a-option
          >
        </a-select>
        <a-button type="primary" class="btn-reset" size="large" @click="open"
          >开启巷道</a-button
        >
        <a-button type="primary" class="btn-reset" size="large" @click="close"
          >关闭巷道</a-button
        >
      </div>
    </div>
  </a-modal>
  <!-- 修改 -->
  <a-modal
    :visible="changedModal"
    unmount-on-close
    @cancel="changedModal = false"
    @ok="changedOK"
  >
    <template #title> 数据修改 </template>
    <a-space direction="vertical" fill>
      <a-form ref="formRef" :model="form" :rules="rules">
        <a-form-item field="rowNo" label="巷道">
          <a-select
            v-model="form.rowNo"
            placeholder="巷道选择"
            default-value=""
          >
            <a-option value="road1">巷道一</a-option>
            <a-option value="road2">巷道二</a-option>
            <a-option value="road3">巷道三</a-option>
            <a-option value="road4">巷道四</a-option>
            <a-option value="road5">巷道五</a-option>
            <a-option value="road6">巷道六</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="status" label="货位状态">
          <a-select
            v-model="form.status"
            placeholder="货位状态"
            default-value=""
          >
            <a-option
              v-for="task of statusChoice"
              :key="task.value"
              :value="task.value"
              :label="task.label"
            />
          </a-select>
        </a-form-item>
        <a-form-item field="isEmpty" label="是否空箱">
          <a-select
            v-model="form.isEmpty"
            placeholder="是否空箱"
            default-value=""
          >
            <a-option
              v-for="item of isEmptyChoice"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </a-select>
        </a-form-item>
        <a-form-item field="startLotNo" label="货位编码">
          <a-input v-model="form.shelvesCode"></a-input>
        </a-form-item>
        <a-form-item field="productCode" label="料箱编码">
          <a-input v-model="form.palletCode"></a-input>
        </a-form-item>
        <a-form-item field="hierarchy" label="所属层级">
          <a-input v-model="form.hierarchy"></a-input>
        </a-form-item>
        <a-form-item field="col" label="所属列级">
          <a-input v-model="form.col"></a-input>
        </a-form-item>
      </a-form>
    </a-space>
  </a-modal>
</template>

<style scoped>
  .grid-demo {
    margin-top: 15px;
  }
  .btn-group {
    margin-top: 15px;
  }

  .btn-reset {
    margin-left: 10px;
  }
  .div-flex {
    display: flex;
  }
</style>
